package labuladong.滑动窗口;

import java.util.*;

public class 所有字母异位词 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(findAnagrams("cbaebabacd", "abc")));
    }

    public static int[] findAnagrams(String s, String t) {
        Map<Character, Integer> need = new HashMap<>();
        Map<Character, Integer> window = new HashMap<>();
        for (char c : t.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0)+1);
        }
        int left = 0, right = 0;
        int valid = 0;
        List<Integer> list = new ArrayList<>();
        while (right < s.length()) {
            char c1 = s.charAt(right);
            right++;
            if (need.containsKey(c1)) {
                window.put(c1, window.getOrDefault(c1, 0)+1);
                if (need.get(c1) == window.get(c1)) {
                    valid++;
                }
            }

            while (right - left >= need.size()) {
                if (valid == need.size()) {
                    list.add(left);
                }
                char c2 = s.charAt(left);
                left++;
                if (need.containsKey(c2)) {
                    if (window.get(c2) == need.get(c2)) {
                        valid--;
                    }
                    window.put(c2, window.get(c2)-1);
                    if (window.get(c2) <= 0) {
                        window.remove(c2);
                    }
                }
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}
